package com.web.fsc.dao.impl;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.web.fsc.dao.IBaseDAO;

@Repository
@Transactional
public class BaseDAOImpl<T> implements IBaseDAO<T> {

	@Autowired
	private SessionFactory sessionFactory;

	private Session session;

	public Session getSession() {
		if (session == null)
			return this.sessionFactory.openSession();
		return session;
	}

	@Override
	public Serializable save(T t) {
		// TODO Auto-generated method stub
		return getSession().save(t);
	}

	@Override
	public void update(T t) {
		// TODO Auto-generated method stub
		getSession().saveOrUpdate(t);
	}

	@Override
	public void delete(Class<T> entityClazz, Long id) {
		// TODO Auto-generated method stub
		Session session=getSession();
		Transaction tr = session.getTransaction();
		tr.begin();
		T t = session.load(entityClazz, id);
		session.delete(t);
		tr.commit();
		System.out.println("commit");
	}

	@Override
	public List<T> findByNameLike(Class<T> entityClazz, String category, String name) {
		// TODO Auto-generated method stub
		return find("select ?1 from ?0 t where t.?1 =?2", entityClazz.getSimpleName(), category, name);
	}

	@SuppressWarnings("unchecked")
	public List<T> find(String hql, Object... params) {
		Query query = getSession().createQuery(hql);
		for (int i = 0; i < params.length; i++) {
			query.setParameter(i + "", params[i]);
		}
		return query.list();
	}

	@Override
	public T findById(Class<T> entityClazz, Long id) {
		// TODO Auto-generated method stub
		return getSession().get(entityClazz, id);
	}

	@Override
	public List<T> findAll(Class<T> entityClazz) {
		// TODO Auto-generated method stub
		return find("from " + entityClazz.getSimpleName());
	}

}
